﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataLayer.Entities;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.SqlCommand;

namespace DataLayer.Implementations
{
    public class UserOrderApplication : GeneralApplication<UserOrder>
    {
        public void Save(UserOrder userOrder)
        {
            if (userOrder.UserOrderId == null)
            {
                Save(userOrder, 0);
            }
            else
            {
                Save(userOrder, userOrder.UserOrderId.Value);
            }
        }

        public IList<UserOrder> GetActiveUsersOrderedByUserOrder()
        {
            using (var session = model.GetSessionFactory().OpenSession())
            {
                ICriteria criteria = session
                    .CreateCriteria(typeof(UserOrder));
                criteria.CreateCriteria("User", "U", JoinType.InnerJoin);
                criteria.Add(Expression.Eq("U.IsActive", true));
                IList<UserOrder> result = criteria.List<UserOrder>();
                return result.OrderBy(x => x.OrderNumber).ToList();
            }
        }

        public UserOrder GetByUserId(int userId)
        {
            List<ICriterion> conditions = new List<ICriterion>();
            conditions.Add(Restrictions.Eq("User.UserId", userId));

            return model.GetByCriterion<UserOrder>(conditions).FirstOrDefault();
        }

        public int GetNextUserOrder()
        {
            using (var session = model.GetSessionFactory().OpenSession())
            {
                var max = session.CreateCriteria(typeof(UserOrder))
                  .SetProjection(Projections.Max("OrderNumber"))
                  .UniqueResult();
                return (max == null ? 0 : (int)max) + 1;
            }
        }
    }
}
